import traceback

from fastapi import APIRouter, Depends, Body, HTTPException
from sqlalchemy.orm import Session

from app.sql_app import models
from app.sql_app.database import get_db
from app.sql_app.schemas import M3u8Resource, YoutubeResource

router = APIRouter(tags=['Resource'], prefix='/resource')


@router.post("/m3u8", summary="提交m3u8资源链接", response_model=dict)
def m3u8(
        db: Session = Depends(get_db),
        m3u8_resource_list: list[M3u8Resource] = Body(..., description="相关信息")
):
    try:
        for m3u8_resource in m3u8_resource_list:
            filename = f"{m3u8_resource.title}-{m3u8_resource.time_}-{m3u8_resource.author}.mp4".replace(" ", "")
            if db.query(models.Resource).filter(models.Resource.filename == filename).first():
                print("exists", filename)
                continue
            m3u8_resource_dict = m3u8_resource.dict()
            del m3u8_resource_dict["uri"]
            resource = models.Resource(
                uri=m3u8_resource.uri,
                filename=filename,
                filetype=0,
                extends=m3u8_resource_dict
            )
            db.add(resource)
            db.commit()
    except Exception as e:
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=str(e))
    return {"success": True}


@router.post("/youtube", summary="提交youtube数据", response_model=dict)
def m3u8(
        db: Session = Depends(get_db),
        youtube_resources: list[YoutubeResource] = Body(..., description="相关信息")
):
    try:
        for youtube_resource in youtube_resources:
            models_first = db.query(models.Resource).filter(models.Resource.url == youtube_resource.url).first()
            if not models_first:
                resource = models.Resource(
                    filetype=1,
                    **youtube_resource.dict()
                )
                db.add(resource)
        db.commit()
    except Exception as e:
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=str(e))
    return {"success": True}
